<script setup lang="ts">
import { ref, onMounted, h } from 'vue';
import { Page } from '@vben/common-ui';
import { NDataTable, NPagination, NButton, NModal, NForm, NFormItem, NInput, NInputNumber, NTag, useMessage } from 'naive-ui';
import { getComponentList, createComponent, updateComponent, deleteComponent, type Component } from '#/api/agent-platform/component';

const columns = [
  { key: 'id', title: 'ID', width: 80 },
  { key: 'name', title: '组件名称' },
  { key: 'description', title: '描述', ellipsis: true },
  { key: 'agent_provider_id', title: '提供商ID' },
  { key: 'version', title: '版本', render: (row: any) => h(NTag, { type: 'info' }, { default: () => row.version }) },
  { key: 'created_at', title: '创建时间' },
  {
    key: 'actions',
    title: '操作',
    render(row: any) {
      return [
        h(NButton, { size: 'small', type: 'primary', onClick: () => handleDetail(row) }, { default: () => '详情' }),
        h(NButton, { size: 'small', type: 'info', class: 'ml-2', onClick: () => handleEdit(row) }, { default: () => '编辑' }),
        h(NButton, { size: 'small', type: 'error', class: 'ml-2', onClick: () => handleDelete(row) }, { default: () => '删除' }),
      ];
    },
  },
];

// 详情表格列定义
const detailColumns = [
  { key: 'field', title: '字段' },
  { key: 'value', title: '值' },
];

const data = ref<Component[]>([]);
const total = ref(0);
const page = ref(1);
const pageSize = ref(10);
const loading = ref(false);
const message = useMessage();

// 搜索条件
const searchForm = ref({
  keyword: '',
  agent_provider_id: undefined as number | undefined,
  version: '',
});

// 弹窗相关
const showModal = ref(false);
const modalType = ref<'create'|'edit'|'detail'>('create');
const modalTitle = ref('');
const formModel = ref<Component>({
  name: '',
  description: '',
  agent_provider_id: 0,
  version: '',
  input: null,
  output: null,
});
const formLoading = ref(false);
const detailData = ref<any[]>([]);

async function fetchData() {
  loading.value = true;
  try {
    const params: any = {
      page: page.value,
      size: pageSize.value,
      ...searchForm.value,
    };

    // 过滤掉空值
    Object.keys(params).forEach((key: string) => {
      if (params[key] === null || params[key] === '' || params[key] === undefined) {
        delete params[key];
      }
    });

    const res = await getComponentList(params);
    data.value = res.result?.items || [];
    total.value = res.result?.total || 0;
  } catch (error) {
    console.error('获取组件列表失败:', error);
    message.error('获取组件列表失败');
    data.value = [];
  } finally {
    loading.value = false;
  }
}

onMounted(fetchData);

function handlePageChange(p: number) {
  page.value = p;
  fetchData();
}

function handlePageSizeChange(s: number) {
  pageSize.value = s;
  page.value = 1;
  fetchData();
}

function handleSearch() {
  page.value = 1;
  fetchData();
}

function handleReset() {
  searchForm.value = {
    keyword: '',
    agent_provider_id: undefined,
    version: '',
  };
  page.value = 1;
  fetchData();
}

function handleCreate() {
  modalType.value = 'create';
  modalTitle.value = '新建组件';
  formModel.value = {
    name: '',
    description: '',
    agent_provider_id: 0,
    version: '',
    input: null,
    output: null,
  };
  showModal.value = true;
}

function handleEdit(row: Component) {
  modalType.value = 'edit';
  modalTitle.value = '编辑组件';
  formModel.value = { ...row };
  showModal.value = true;
}

function handleDetail(row: Component) {
  modalType.value = 'detail';
  modalTitle.value = '组件详情';
  formModel.value = { ...row };

  // 转换为表格数据格式
  detailData.value = [
    { field: 'ID', value: formModel.value.id || '-' },
    { field: '组件名称', value: formModel.value.name || '-' },
    { field: '描述', value: formModel.value.description || '-' },
    { field: '提供商ID', value: formModel.value.agent_provider_id || '-' },
    { field: '版本', value: formModel.value.version || '-' },
    { field: '输入配置', value: formModel.value.input ? JSON.stringify(formModel.value.input, null, 2) : '-' },
    { field: '输出配置', value: formModel.value.output ? JSON.stringify(formModel.value.output, null, 2) : '-' },
    { field: '创建时间', value: formModel.value.created_at || '-' },
    { field: '创建者', value: formModel.value.created_by || '-' },
  ];

  showModal.value = true;
}

async function handleDelete(row: Component) {
  if (confirm('确定要删除该组件吗？')) {
    try {
      await deleteComponent(row.id!);
      message.success('删除成功');
      fetchData();
    } catch (error) {
      console.error('删除失败:', error);
      message.error('删除失败');
    }
  }
}

async function handleModalOk() {
  formLoading.value = true;
  try {
    if (modalType.value === 'create') {
      // 验证必填字段
      if (!formModel.value.name || !formModel.value.description || !formModel.value.agent_provider_id || !formModel.value.version) {
        message.error('请填写组件名称、描述、提供商ID和版本');
        return;
      }
      await createComponent(formModel.value);
      message.success('新建成功');
    } else if (modalType.value === 'edit') {
      // 验证必填字段
      if (!formModel.value.name || !formModel.value.description || !formModel.value.version) {
        message.error('请填写组件名称、描述和版本');
        return;
      }
      const updateData = {
        name: formModel.value.name,
        description: formModel.value.description,
        version: formModel.value.version,
        input: formModel.value.input,
        output: formModel.value.output,
      };
      await updateComponent(formModel.value.id!, updateData);
      message.success('编辑成功');
    }
    showModal.value = false;
    fetchData();
  } catch (error) {
    console.error('操作失败:', error);
    const errorMsg = modalType.value === 'create' ? '新建失败' : '编辑失败';
    message.error(errorMsg);
  } finally {
    formLoading.value = false;
  }
}
</script>

<template>
  <Page description="Agent组件管理" title="组件管理">
    <!-- 搜索条件 -->
    <div class="mb-4">
      <NForm :model="searchForm" inline>
        <NFormItem label="关键词">
          <NInput v-model:value="searchForm.keyword" placeholder="搜索名称或描述" style="width: 200px" />
        </NFormItem>
        <NFormItem label="提供商ID">
          <NInputNumber v-model:value="searchForm.agent_provider_id" placeholder="请输入提供商ID" style="width: 150px" />
        </NFormItem>
        <NFormItem label="版本">
          <NInput v-model:value="searchForm.version" placeholder="请输入版本" style="width: 150px" />
        </NFormItem>
        <NFormItem>
          <NButton type="primary" @click="handleSearch">搜索</NButton>
          <NButton class="ml-2" @click="handleReset">重置</NButton>
        </NFormItem>
      </NForm>
    </div>

    <div class="mb-4 flex justify-end">
      <NButton type="primary" @click="handleCreate">新建组件</NButton>
    </div>

    <NDataTable :columns="columns" :data="data" :loading="loading" />
    <div class="mt-4 flex justify-end">
      <NPagination
        v-model:page="page"
        v-model:page-size="pageSize"
        :item-count="total"
        show-size-picker
        :page-sizes="[10, 20, 50, 100]"
        @update:page="handlePageChange"
        @update:page-size="handlePageSizeChange"
      />
    </div>

    <NModal v-model:show="showModal" :title="modalTitle" preset="dialog" :loading="formLoading" :mask-closable="false" :style="{ width: modalType === 'detail' ? '900px' : '800px' }">
      <!-- 新建/编辑表单 -->
      <NForm :model="formModel" label-width="120" v-if="modalType === 'create' || modalType === 'edit'">
        <NFormItem label="组件名称" path="name">
          <NInput v-model:value="formModel.name" placeholder="请输入组件名称" />
        </NFormItem>
        <NFormItem label="描述" path="description">
          <NInput v-model:value="formModel.description" type="textarea" placeholder="请输入组件描述" />
        </NFormItem>
        <NFormItem label="提供商ID" path="agent_provider_id">
          <NInputNumber v-model:value="formModel.agent_provider_id" placeholder="请输入提供商ID" style="width: 100%" :disabled="modalType === 'edit'" />
        </NFormItem>
        <NFormItem label="版本" path="version">
          <NInput v-model:value="formModel.version" placeholder="请输入版本，如: 1.0.0" />
        </NFormItem>
        <NFormItem label="输入配置" path="input">
          <NInput
            v-model:value="formModel.input"
            type="textarea"
            placeholder="请输入JSON格式的输入配置"
            :autosize="{ minRows: 3, maxRows: 6 }"
          />
        </NFormItem>
        <NFormItem label="输出配置" path="output">
          <NInput
            v-model:value="formModel.output"
            type="textarea"
            placeholder="请输入JSON格式的输出配置"
            :autosize="{ minRows: 3, maxRows: 6 }"
          />
        </NFormItem>
      </NForm>

      <!-- 详情展示 -->
      <NDataTable v-else :columns="detailColumns" :data="detailData" :bordered="false" />

      <template #action v-if="modalType !== 'detail'">
        <NButton type="primary" :loading="formLoading" @click="handleModalOk">确定</NButton>
        <NButton class="ml-2" @click="() => (showModal = false)">取消</NButton>
      </template>
      <template #action v-else>
        <NButton @click="() => (showModal = false)">关闭</NButton>
      </template>
    </NModal>
  </Page>
</template>

<style scoped></style>
